#!/bin/bash
# enable_auto_boot.sh - 修复版开机自启动

# 获取脚本所在目录
SCRIPT_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]:-$0}")")"
cd "$SCRIPT_DIR" || { echo "❌ 无法切换到项目目录"; exit 1; }

echo "🔧 开始设置开机自启动（修复版）..."

# 服务配置
SERVICE_NAME="kgqa-service"
SERVICE_FILE="/etc/systemd/system/$SERVICE_NAME.service"
USER_NAME=$(whoami)
PYTHON_PATH=$(which python)

echo "📁 项目目录: $SCRIPT_DIR"
echo "👤 运行用户: $USER_NAME"
echo "🐍 Python路径: $PYTHON_PATH"
echo "🛠️  服务名: $SERVICE_NAME"

# 检查必要的文件
if [ ! -f "app_stream.py" ]; then
    echo "❌ 错误: 找不到 app_stream.py 文件"
    exit 1
fi

# 停止当前可能运行的服务
./kill.sh

# 创建 systemd 服务文件（使用 simple 类型）
echo "📄 创建 systemd 服务文件: $SERVICE_FILE"

sudo tee "$SERVICE_FILE" > /dev/null <<EOF
[Unit]
Description=KGQA FastAPI Service
After=network.target

[Service]
Type=simple
User=$USER_NAME
WorkingDirectory=$SCRIPT_DIR
ExecStart=$PYTHON_PATH app_stream.py
Restart=always
RestartSec=10
StandardOutput=journal
StandardError=journal

[Install]
WantedBy=multi-user.target
EOF

if [ $? -ne 0 ]; then
    echo "❌ 错误: 创建服务文件失败，请检查权限"
    exit 1
fi

echo "✅ 服务文件创建成功"

# 重新加载 systemd 配置
echo "🔄 重新加载 systemd 配置..."
sudo systemctl daemon-reload

# 启用开机自启动
echo "🚀 启用开机自启动..."
sudo systemctl enable $SERVICE_NAME

# 启动服务测试
echo "🔍 测试启动服务..."
sudo systemctl start $SERVICE_NAME
sleep 3

echo ""
echo "📋 服务状态:"
sudo systemctl status $SERVICE_NAME --no-pager -l

echo ""
echo "🎉 设置完成!"
echo "📋 服务管理命令:"
echo "  启动: sudo systemctl start $SERVICE_NAME"
echo "  停止: sudo systemctl stop $SERVICE_NAME"
echo "  状态: sudo systemctl status $SERVICE_NAME"
echo "  日志: sudo journalctl -u $SERVICE_NAME -f"